package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.TSubSystemBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.TSubSystemMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.mysql.cj.util.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

public class TSubSystemAdd implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);

		try {
			TSubSystemBean tSubSystemBean = JsonUtils.objectToPojo(req.getData(), TSubSystemBean.class);
			// ip校验
			if (!StringUtils.isNullOrEmpty(tSubSystemBean.getAllowIp()) && !CommonUtils.isIpAddress(tSubSystemBean.getAllowIp())
					&& !CommonUtils.isIpAddressSegment(tSubSystemBean.getAllowIp())) {
				info.setCode(Constant.ILLEGAL_PARAMETER);
				info.setDescription("服务允许IP地址段请输入正确的ip格式");
				return info;
			}
			if (!StringUtils.isNullOrEmpty(tSubSystemBean.getForbidIp()) && (!CommonUtils.isIpAddress(tSubSystemBean.getForbidIp())
					&& !CommonUtils.isIpAddressSegment(tSubSystemBean.getForbidIp()))) {
				info.setCode(Constant.ILLEGAL_PARAMETER);
				info.setDescription("服务禁止IP地址段请输入正确的ip格式");
				return info;
			}
			TSubSystemMapper mapper = factory.getMapper(TSubSystemMapper.class);
			if (mapper.getTSubSystemByCode(tSubSystemBean.getSystemCode()) != null) {
				info.setCode(Constant.MESSAGE_INT_FAIL);
				info.setDescription("已存在与 " + tSubSystemBean.getSystemCode() + " 相同编号的信息");
			} else {
				tSubSystemBean.setStatus(1);// 默认启动
				tSubSystemBean.setCreateName(userInfo.getUserInfo().getName());
				tSubSystemBean.setCreateTime(CommonUtils.getCurrentTime());
				mapper.insertTSubSystem(tSubSystemBean);
			}
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
